package com.devo.icecream.ui.home

import androidx.compose.animation.core.*
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.LocalOverscrollConfiguration
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.grid.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.drawWithContent
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.BlendMode
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import com.devo.icecream.R
import com.devo.icecream.data.Advertising
import com.devo.icecream.data.ProductBean
import com.devo.icecream.ui.theme.IcecreamTheme
import com.devo.icecream.ui.theme.Main
import com.devo.icecream.ui.widget.AppButton
import com.devo.icecream.ui.widget.AppPageView
import com.devo.icecream.utils.Time
import com.devo.icecream.utils.noRippleClickable
import kotlinx.coroutines.delay


@Composable
fun HomeScreen(
    status: BusinessStatus = BusinessStatus.OPEN,
    products: List<ProductBean> = arrayListOf(),
    advertising: List<Advertising> = arrayListOf(),
    onHideClick: () -> Unit = {},
    onItemClick: (ProductBean) -> Unit = {},
    onDiyClick: () -> Unit = {}
) {


    Scaffold(floatingActionButton = {
        if (status is BusinessStatus.OPEN) BuildFloatActionButton(
            onDiyClick
        )
    }) {

        Column(
            modifier = Modifier
                .padding(it)
                .fillMaxWidth(),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {


            Image(
                modifier = Modifier
                    .noRippleClickable {
                        onHideClick()
                    }
                    .padding(vertical = 30.dp)
                    .fillMaxWidth(fraction = 0.35f)
                    .wrapContentHeight(),
                painter = painterResource(id = R.mipmap.logo),
                contentScale = ContentScale.FillWidth,
                contentDescription = "logo"
            )

            when (status) {
                is BusinessStatus.OPEN -> {
                    ProductLayout(products, advertising, onItemClick, onDiyClick)
                }
                is BusinessStatus.STOP -> {
                    StopLayout(modifier = Modifier.weight(1f))
                }
                is BusinessStatus.CLOSE -> {
                    CloseLayout(
                        range = status.range,
                        modifier = Modifier.weight(1f)
                    )
                }
            }

        }
    }
}

@Composable
fun BuildFloatActionButton(onDiyClick: () -> Unit = {}) {
    Box(Modifier.padding(bottom = 80.dp)) {

        FloatingActionButton(
            modifier = Modifier
                .wrapContentSize(),
            shape = RoundedCornerShape(50),
            backgroundColor = Main,
            onClick = { onDiyClick() },
        ) {
            Text(
                modifier = Modifier.padding(horizontal = 30.dp, vertical = 10.dp),
                text = "自选小料",
                fontSize = 42.sp,
                color = Color.White,
                fontWeight = FontWeight.Bold
            )
        }
    }
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun ProductLayout(
    products: List<ProductBean> = listOf(),
    advertising: List<Advertising> = listOf(),
    onItemClick: (ProductBean) -> Unit = {},
    onDiyClick: () -> Unit = {},
) {
    CompositionLocalProvider(LocalOverscrollConfiguration provides null) {
        Column {
            LazyVerticalGrid(
                modifier = Modifier
                    .weight(1f)
                    .padding(5.dp, 0.dp)
                    .graphicsLayer { alpha = 0.99F }
                    .drawWithContent {
                        val colors = listOf(Color.Transparent, Color.Black)
                        drawContent()
                        drawRect(
                            brush = Brush.verticalGradient(colors, endY = 24f),
                            blendMode = BlendMode.DstIn
                        )
                    },
                columns = GridCells.Fixed(2),
                contentPadding = PaddingValues(32.dp),

                verticalArrangement = Arrangement.spacedBy(32.dp),
                horizontalArrangement = Arrangement.spacedBy(32.dp)
            ) {

                item(span = { GridItemSpan(maxLineSpan) }) {
                    DIYLoopPage(advertising) {
                        onDiyClick()
                    }
                }
                itemsIndexed(products) { inx, item ->
                    ProductItem(item) {
                        onItemClick(item)
                    }
                }
            }

            DiyClickBar(onDiyClick)

        }

    }
}

@Composable
fun DiyClickBar(onDiyClick: () -> Unit = {}) {

    val animatedFloat = remember { Animatable(0.5f) }

    LaunchedEffect(animatedFloat) {
        while (true) {
            delay(200) // to avoid repeated delays
            animatedFloat.animateTo(
                targetValue = 0.8f,
                animationSpec = infiniteRepeatable(
                    animation = tween(700, easing = FastOutSlowInEasing),
                    repeatMode = RepeatMode.Reverse
                )
            )
        }
    }
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .height(80.dp)
            .background(Main)
            .noRippleClickable { onDiyClick() },
        horizontalArrangement = Arrangement.Center,
        verticalAlignment = Alignment.CenterVertically,
    ) {

        Image(
            modifier = Modifier
                .scale(animatedFloat.value)
                .fillMaxHeight(),
            painter = painterResource(id = R.mipmap.click),
            contentScale = ContentScale.FillHeight,
            contentDescription = ""
        )

        Spacer(modifier = Modifier.width(16.dp))

        Text(
            text = "DIY您喜欢的口味",
            color = Color.White,
            style = MaterialTheme.typography.h1
        )
    }

}


@Composable
private fun StopLayout(modifier: Modifier = Modifier) {
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .wrapContentHeight()
            .then(modifier),
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .align(Alignment.Center)
                .wrapContentHeight(),
            horizontalAlignment = Alignment.CenterHorizontally,
        ) {
            Image(
                modifier = Modifier
                    .fillMaxWidth(0.25f)
                    .aspectRatio(695 / 510f),
                painter = painterResource(id = R.mipmap.stop),
                contentScale = ContentScale.FillWidth,
                contentDescription = null
            )

            Spacer(modifier = Modifier.height(22.dp))

            Text(
                text = "设备正在停机检修中",
                style = MaterialTheme.typography.h1
            )

            Spacer(modifier = Modifier.height(16.dp))

            Text(
                text = "设备正在停机检修中，给您带来的不便敬请谅解",
                style = MaterialTheme.typography.subtitle1,
                textAlign = TextAlign.Center
            )

        }
    }
}


@Composable
private fun CloseLayout(range: ClosedRange<Time>, modifier: Modifier = Modifier) {
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .wrapContentHeight()
            .then(modifier),
        contentAlignment = Alignment.Center
    ) {
        Column(
            modifier = Modifier
                .wrapContentHeight()
                .align(Alignment.Center),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Image(
                modifier = Modifier
                    .fillMaxWidth(0.25f)
                    .aspectRatio(695 / 510f),
                painter = painterResource(id = R.mipmap.close),
                contentScale = ContentScale.FillWidth,
                contentDescription = null
            )
            Spacer(modifier = Modifier.height(22.dp))
            Text(
                text = "打烊中",
                style = MaterialTheme.typography.h1
            )
            Spacer(modifier = Modifier.height(16.dp))
            Text(
                text = "营业时间：${range.start}~${range.endInclusive}",
                style = MaterialTheme.typography.subtitle1,
                textAlign = TextAlign.Center
            )

        }
    }
}

@Composable
private fun ProductItem(item: ProductBean, onClick: () -> Unit = {}) {
    Card(
        modifier = Modifier.fillMaxSize(),
        shape = RoundedCornerShape(16.dp),
        elevation = 0.dp,
        contentColor = Color.White
    ) {
        Box {
            Column(modifier = Modifier.fillMaxSize()) {

                AsyncImage(
                    modifier = Modifier
                        .fillMaxWidth()
                        .aspectRatio(0.8f),
                    model = item.coverPic,
                    contentDescription = null,
                    contentScale = ContentScale.Crop
                )

                Column(modifier = Modifier.padding(16.dp, 8.dp)) {

                    TitleAndPrice(item = item)

                    Spacer(modifier = Modifier.height(4.dp))

                    Text(
                        modifier = Modifier.padding(10.dp, 0.dp),
                        text = "热量：${item.power}Kcal\n配料: ${item.ingredientStr}",
                        style = MaterialTheme.typography.subtitle1.let {
                            it.copy(lineHeight = (it.fontSize.value + 10.sp.value).sp)
                        }
                    )

                    Spacer(modifier = Modifier.height(16.dp))

                    AppButton(
                        modifier = Modifier.align(Alignment.End),
                        enable = item.isAvailable,
                        text = "立即制作"
                    ) {
                        if (item.isAvailable) {
                            onClick()
                        }
                    }

                    Spacer(modifier = Modifier.height(20.dp))
                }
            }
            if (!item.isAvailable) {
                Image(
                    modifier = Modifier
                        .fillMaxWidth(0.3f)
                        .padding(bottom = 5.dp, end = 5.dp)
                        .wrapContentHeight()
                        .align(Alignment.BottomEnd),
                    painter = painterResource(id = R.mipmap.ample),
                    contentScale = ContentScale.FillWidth,
                    contentDescription = "ample"
                )
            }

        }
    }

}

@Composable
private fun TitleAndPrice(item: ProductBean) {
    Row(
        modifier = Modifier
            .padding(16.dp, 8.dp)
            .height(IntrinsicSize.Max)
            .fillMaxWidth(),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(
            text = item.name,
            modifier = Modifier.weight(1f),
            style = MaterialTheme.typography.h3
        )

        Text(
            text = buildAnnotatedString {
                withStyle(
                    SpanStyle(
                        fontSize = MaterialTheme.typography.h3.fontSize,
                        color = Main
                    )
                ) {
                    append("￥")
                }
                withStyle(
                    SpanStyle(
                        fontSize = MaterialTheme.typography.h2.fontSize,
                        fontWeight = MaterialTheme.typography.h2.fontWeight,
                        color = Main
                    )
                ) {
                    append(item.salePrice.toString())
                }
            }
        )
    }

}

@Composable
fun DIYLoopPage(
    advertising: List<Advertising> = listOf(),
    onItemClick: (index: Int) -> Unit = {}
) {

    Box(
        modifier = Modifier
            .fillMaxWidth()
            .height(580.dp)
            .clip(RoundedCornerShape(4)),
        contentAlignment = Alignment.Center
    ) {
        if (advertising.isEmpty()) {
            Image(
                painter = painterResource(id = R.mipmap.ad_back),
                contentDescription = "",
                contentScale = ContentScale.FillBounds
            )
        } else {
            AppPageView(
                Modifier.fillMaxSize(),
                auto = true,
                urls = advertising.map { it.picture },
                onItemClick = onItemClick
            )
        }

        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(Color(0x4f000000)),
            contentAlignment = Alignment.Center,
        ) {

            Text(
                text = "DIY专区",
                fontWeight = FontWeight.Bold,
                fontSize = 120.sp,
                color = Color.White,
                textAlign = TextAlign.Center,
                fontStyle = FontStyle.Italic
            )
        }
    }

}


@OptIn(ExperimentalFoundationApi::class)
@Preview(heightDp = 1920, widthDp = 1080)
@Composable
private fun ProductPreview() {
    val list = arrayListOf(
        ProductBean(
            coverPic = "http://120.78.159.86:6689/file/202203/4817df372acb22f88fa48e11e438c659.png",
            spaceName = "高科技",
            name = "sss",
            _salePrice = 1,
            menuName = "西撇菜单fdafdafdafdafdafafdafdafdafdafdafdsa"
        ),
        ProductBean(
            coverPic = "http://120.78.159.86:6689/file/202203/4817df372acb22f88fa48e11e438c659.png",
            spaceName = "高科技",
            name = "sss",
            _salePrice = 1,
            menuName = "西撇菜单"
        ),
        ProductBean(
            coverPic = "http://120.78.159.86:6689/file/202203/4817df372acb22f88fa48e11e438c659.png",
            spaceName = "高科技",
            name = "sss",
            _salePrice = 98,
            menuName = "西撇菜单"
        )


    )
    IcecreamTheme() {

        LazyVerticalGrid(columns = GridCells.Fixed(2)) {
            items(list) {
                ProductItem(
                    item = it
                )
            }
        }
    }
}

@Preview(heightDp = 1920, widthDp = 1080)
@Composable
private fun HomePreview() {
    IcecreamTheme {
        HomeScreen()
    }
}

